package com.cgah

import grails.test.*
import com.cgah.Bid
import groovy.mock.interceptor.MockFor
import org.apache.ivy.core.resolve.IvyNodeCallers.Caller
import com.cgah.BidController

class BidControllerTests extends GroovyTestCase {

    def session
    def params
    def redirectParams
    def flash

    /** Setup metaclass fixtures for mocking.  */
    void setUp() {
        super.setUp()
        session = [:]
        BidController.metaClass.getSession = {-> session }

        params = [:]
        BidController.metaClass.getParams = {-> params }

        redirectParams = [:]
        BidController.metaClass.redirect = { Map args -> redirectParams = args  }

        flash = [:]
        BidController.metaClass.getFlash = {-> flash }

        def logger = new Expando(debug: { println it }, info: { println it },
                warn: { println it }, error: { println it })
        BidController.metaClass.getLog = {-> logger }
    }

    protected void tearDown() {
        flash = null;
        redirectParams = null;
        params = null;
        session = null;
        super.tearDown()
    }

    //L-7: The detail page for the listing allows a new bid to be placed (unit test)
    // test for the existance of the addBid method? and that save is called?
    void testAddBidExists() {
        def mocker = new MockFor(Bid.class)  // create the Mock support
        mocker.demand.save() { return false } // used once and throws exception
        mocker.use {                                  // start using the Mock
            def bidController = new BidController()
            assertNotNull(bidController.addBid());
        }
    }



    void testAddBidStoresFailedMessageInFlashWhenSaveFails() {
        def mocker = new MockFor(Bid.class)  // create the Mock support
        mocker.demand.save() { return false } // used once and throws exception
        mocker.use {                                  // start using the Mock
            def bidController = new BidController()
            bidController.addBid();
            assertTrue(flash.message.toString().contains("FAILED"));
        }
    }


    void testAddBidStoresSuccessMessageInFlashWhenSuccessful() {
        def mocker = new MockFor(Bid.class)  // create the Mock support
        mocker.demand.save() { return true } // used once and throws exception
        mocker.use {                                  // start using the Mock
            def bidController = new BidController()
            bidController.addBid();
            assertTrue(flash.message.toString().contains("saved successfully"));
        }
    }



}
